/********************************************************/
/*	Author:		gong_libin			*/
/*	Date:		2017_11_01			*/
/*	File:		CmAdminTest.cpp			*/
/********************************************************/

#include "CmAdmin.h"
#include "CmEpoll.h"
#include "CmConfig.h"

int CmAdminTestAccept(int iSocket)
{
	CM_PRINT("Socket: %d\n", iSocket);

	CmNet::CCmTcp CTcp;
	char szSend[CM_PACKET] = { 0 };
	char szRecv[CM_PACKET] = { 0 };
	const char* pszHtml = "<html>\r\n<head>\r\n<title>Hello</title>\r\n</head>\r\n<body>\r\n<p>This is a test for Adx!</p>\r\n</body>\r\n</html>";

	CTcp.CmNetSetSocket(iSocket);

	if (CTcp.CmNetRecv((UCHAR*)szRecv, CM_PACKET) > 0) {
		sprintf(szSend, "HTTP/1.1 200 OK\r\nContent-type: text/html\r\nContent-Length: %d\r\n%s\r\n\r\n", (int)strlen(pszHtml), pszHtml);
		CTcp.CmNetSend((UCHAR*)szSend, strlen(szSend));
	}

	return CM_SUCCESS;
}

void* CmAdminTestThread(void* pPara)
{
	char szPort[CM_BUFFER] = {'\0'};
	CmNet::CCmEpoll* pCEpoll = new CmNet::CCmEpoll();

	memcpy(szPort, pPara, strlen((char*)pPara));
	if (CM_SUCCESS == pCEpoll->CmEpollTcpInit(szPort)) {
		pCEpoll->CmEpollSetFunction(CmAdminTestAccept);
		pCEpoll->CmEpollTcpWait();
	}

	return CM_SUCCESS;
}

void CmAdminTestServer(CMMAP_C* pCMap)
{
	CmNet::CCmTcp CTcp;
	char* pszPort = NULL;
	CmCls::CCmThread* pCThread = NULL;

	for (CMMAP_C::CM_ITE CIte = pCMap->CmMapBegin(); CIte != pCMap->CmMapEnd(); ++ CIte) {
		pCThread = new CmCls::CCmThread();
		pszPort = CTcp.CmNetUrl((char*)CIte->second.c_str());

		pCThread->CmThreadAttrInit();
		pCThread->CmThreadRoutineSet(CmAdminTestThread);
		pCThread->CmThreadCreate(pszPort);
	}
	pCThread->CmThreadJoin(NULL);

	return;
}

void CmAdminTestClient(CMMAP_C* pCMap)
{
	CCmAdmin CAdmin(*pCMap);
	CAdmin.CmThreadAttrInit();
	CAdmin.CmThreadRoutineSet(CmCls::CmThreadType<CCmAdmin>);
	CAdmin.CmThreadCreate(&CAdmin);
	CAdmin.CmThreadJoin(NULL);

	return;
}

int main(int argc, char* argv[])
{
	CCmConfig CConfig;
	char szFile[] = "../conf/CmAdx.conf";

	if (CM_SUCCESS == CConfig.CmConfigLoad(szFile)) {
		if (argc > 1) {
			CM_PRINT("Mode: CmAdminTestServer\n");
			CmAdminTestServer(CConfig.CmConfigGetCTrans());
		}
		else {
			CM_PRINT("Mode: CmAdminTestClient\n");
			CmAdminTestClient(CConfig.CmConfigGetCTrans());
		}
	}
	else {
		CM_ERROR("Failed to CmConfigLoad\n");
	}

	return CM_SUCCESS;
}
